package cn.sitedev.registry;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author qchen
 * @description 容器式单例
 * @date 2020/9/17 22:52
 */
public class ContainerSingleton {
    private ContainerSingleton() {
    }

    private static Map<String, Object> ioc = new ConcurrentHashMap<>();

    public static Object getInstance(String className) {
        Object instance = null;
        // 通过同步代码块, 保证线程安全
        synchronized (ioc) {
            if (!ioc.containsKey(className)) {
                try {
                    // 容器中没有该key, 则创建后放入容器中
                    instance = Class.forName(className).newInstance();
                    ioc.put(className, instance);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } else {
                // 容器中有该key , 则直接从容器中取
                return ioc.get(className);
            }
        }
        return instance;
    }
}
